package com.globant.adapter;

import java.util.List;

import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import com.globant.domain.PlaceBean;
import com.globant.fragment.MapFragment;
import com.globant.placemaps.R;

public class PlaceAdapter extends BaseAdapter {

	private List<PlaceBean> places;
	public static FragmentActivity placesFragment;
	
	public PlaceAdapter(List<PlaceBean> places) {
		this.places = places;
	}

	@Override
	public int getCount() {
		return places.size();
	}

	@Override
	public Object getItem(int position) {
		return places.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View item = null;
		PlaceHolder holder = null;
		
		if(convertView == null) {
			item = new View(parent.getContext());
		} else {
			item = (View) convertView;
		}
		
        if (item == null || !(item.getTag() instanceof PlaceHolder)) {
            
            LayoutInflater mInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            item = mInflater.inflate(com.globant.placemaps.R.layout.place_item, parent, false);
            
            holder = new PlaceHolder();
            populateView(holder, item, places.get(position));
            item.setTag(holder);
       }else {
           holder = (PlaceHolder) item.getTag();
       }

		return item;
	}
	
	private void populateView(PlaceHolder holder, View item, final PlaceBean placeBean) {
		holder.placeName = (TextView) item.findViewById(R.id.placeName);
		holder.placeDescription = (TextView) item.findViewById(R.id.placeDescription);
		holder.imageMap = (ImageButton) item.findViewById(R.id.imageMap);
		
		holder.placeName.setText(placeBean.getName());
		holder.placeDescription.setText(placeBean.getDescription());
		holder.latitude = placeBean.getLatitude();
		holder.longitude = placeBean.getLongitude();
		
		final int latitude = holder.latitude;
		final int longitude = holder.longitude;
		
		holder.imageMap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				MapFragment map = (MapFragment)placesFragment.getSupportFragmentManager().findFragmentById(R.id.maps);
				map.modifyLocation(latitude, longitude);
			}
		});
		
	}

	class PlaceHolder {
		public TextView placeName;
		public TextView placeDescription;
		public ImageButton imageMap;
		public int latitude;
		public int longitude;
	}

}
